<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2017/4/1
 * Time: 15:56
 */

namespace SDXApi\Service;


use SDXApi\Abstracts\TemplateAbstract;
use SDXApi\Model\SeminarPageModel;

/**
 * Class SeminarAlbumService
 * @package SDXApi\Service
 */
class SeminarAlbumService extends TemplateAbstract
{
	/**
	 * @var SeminarPageModel
	 */
	protected $seminarPageModel;

	/**
	 * SeminarAlbumService constructor.
	 */
	public function __construct()
	{
		$this->seminarPageModel = new SeminarPageModel();
	}

	/**
	 * Created by Jerry
	 * @param array $template
	 * @param int $userId
	 * @param int $wid
	 * @return array|mixed
	 */
	public function handle($template = array(), $userId = 0, $wid = 8)
	{
		$cacheName = 'seminar_template_page_album_' . $template['id'];
		$data = $this->getCache($cacheName);

		if (empty($data)) {
			$data = $this->album($template);

			if (! empty($data)) {
				$this->cacheData($cacheName, $data, mt_rand(3600, 4200));
			}
		}

		return $data;
	}

	/**
	 * 处理专辑数据
	 * Created by Jerry
	 * @param array $template
	 * @return array
	 */
	protected function album($template = array())
	{
		$data = $this->seminarPageModel->find_seminar_template_album_by_template_id($template['id']);

		$albums = $this->getAlbumCover($data);

		$template['album_list'] = $albums;

		if (empty($albums)) {
			$template['album_list'] = array();
		}

		unset($template['font_type'], $template['font_size'], $template['font_content'], $template['font_link'], $template['image_url'], $template['image_link'], $template['image_size'], $template['goods_type'], $template['goods_id'], $template['template_id']);

		return $template;
	}

	/**
	 * 获取专辑封面
	 * Created by Jerry
	 * @param array $albums
	 * @return array|bool
	 */
	protected function getAlbumCover($albums = array())
	{
		if (empty($albums)) {
			return false;
		}

		$albumService = new AlbumService();

		foreach ($albums as $key => $value) {
			$cover = $albumService->getAlbumCover($value['id']);

			if ($cover) {
				$albums[$key]['cover'] = $cover;
			}

		}

		return $albums;
	}
}